package com.situ.stl.api;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.situ.stl.Service.ReserveService;
import com.situ.stl.model.Reserve;
import com.situ.stl.util.JsonResult;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotEmpty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/reserve")
@Validated
public class ReserveApi {

    private static final Logger log = LoggerFactory.getLogger(ReserveApi.class);
    private final ReserveService reserveService;

    // 构造器注入
    public ReserveApi(ReserveService reserveService) {
        this.reserveService = reserveService;
    }

    /**
     * 创建预约
     */
    @PostMapping
    public ResponseEntity<JsonResult<?>> add(@RequestBody Reserve reserve) {
        try {
            int rows = reserveService.add(reserve);
            log.info("创建预约成功，ID：{}", reserve.getId());
            // 成功响应：201状态码 + JsonResult(success=true)
            return ResponseEntity.status(HttpStatus.CREATED)
                    .body(JsonResult.success(reserve));
        } catch (Exception e) {
            log.error("创建预约失败：{}", e.getMessage());
            // 失败响应：400状态码 + 错误信息
            return ResponseEntity.badRequest()
                    .body(JsonResult.fail(400, e.getMessage()));
        }
    }

    /**
     * 删除预约
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<JsonResult<?>> remove(
            @PathVariable @Min(value = 1, message = "ID必须为正整数") Integer id) {
        try {
            int rows = reserveService.remove(id);
            log.info("删除预约成功，ID：{}", id);
            return ResponseEntity.ok(JsonResult.success("删除成功"));
        } catch (Exception e) {
            log.error("删除预约失败，ID：{}，原因：{}", id, e.getMessage());
            return ResponseEntity.badRequest()
                    .body(JsonResult.fail(400, e.getMessage()));
        }
    }

    /**
     * 更新预约信息
     */
    @PutMapping
    public ResponseEntity<JsonResult<?>> edit(@RequestBody Reserve reserve) {
        try {
            int rows = reserveService.edit(reserve);
            log.info("更新预约成功，ID：{}", reserve.getId());
            return ResponseEntity.ok(JsonResult.success(reserve));
        } catch (Exception e) {
            log.error("更新预约失败，ID：{}，原因：{}", reserve.getId(), e.getMessage());
            return ResponseEntity.badRequest()
                    .body(JsonResult.fail(400, e.getMessage()));
        }
    }

    /**
     * 批量更新预约状态（如批量签到）
     */
    @PutMapping("/batchStatus")
    public ResponseEntity<JsonResult<?>> batchUpdateStatus(
            @RequestParam @Min(value = 0, message = "状态值不能为负数") Integer status,
            @RequestBody @NotEmpty(message = "至少选择一条记录") List<Integer> ids) {
        try {
            int rows = reserveService.batchUpdateStatus(status, ids);
            log.info("批量更新预约状态成功，影响条数：{}", rows);
            return ResponseEntity.ok(JsonResult.success(rows));
        } catch (Exception e) {
            log.error("批量更新预约状态失败：{}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(JsonResult.fail(400, e.getMessage()));
        }
    }

    /**
     * 根据ID查询单个预约详情（带关联信息）
     */
    @GetMapping("/{id}")
    public ResponseEntity<JsonResult<?>> getById(
            @PathVariable @Min(value = 1, message = "ID必须为正整数") Integer id) {
        Reserve reserve = reserveService.getById(id);
        if (reserve == null) {
            log.warn("查询预约失败，ID：{}不存在", id);
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(JsonResult.fail(404, "预约记录不存在"));
        }
        return ResponseEntity.ok(JsonResult.success(reserve));
    }

    /**
     * 多条件查询预约（无分页）
     */
    @GetMapping
    public ResponseEntity<JsonResult<?>> search(Reserve reserve) {
        List<Reserve> list = reserveService.search(reserve);
        log.info("多条件查询预约，结果条数：{}", list.size());
        return ResponseEntity.ok(JsonResult.success(list));
    }

    @GetMapping("/page")
    public ResponseEntity<JsonResult<?>> searchByPage(
            @RequestParam(defaultValue = "1") @Min(value = 1) Integer pageNo,
            @RequestParam(defaultValue = "10") @Min(value = 1) Integer pageSize,
            Reserve reserve,
            // 新增：显式接收前端传递的会员姓名和课程名称参数
            @RequestParam(required = false) String memberName,
            @RequestParam(required = false) String courseName
    ) {
        // 调用Service层时，将这两个参数传递进去
        Page<Reserve> page = reserveService.searchByPage(
                pageNo,
                pageSize,
                reserve,
                memberName,
                courseName
        );
        log.info("分页查询预约，页码：{}，每页条数：{}，总条数：{}，搜索条件：会员={},课程={}",
                pageNo, pageSize, page.getTotal(), memberName, courseName);
        return ResponseEntity.ok(JsonResult.success(page));
    }

    /**
     * 查询指定会员的所有预约
     */
    @GetMapping("/member/{memberId}")
    public ResponseEntity<JsonResult<?>> getByMember(
            @PathVariable @Min(value = 1) Integer memberId) {
        List<Reserve> list = reserveService.getByMember(memberId);
        log.info("查询会员[ID:{}]的预约，结果条数：{}", memberId, list.size());
        return ResponseEntity.ok(JsonResult.success(list));
    }

    @GetMapping("/course/{courseId}")
    public ResponseEntity<JsonResult<?>> getByCourse(
            @PathVariable @Min(value = 1, message = "课程ID必须为正整数") Integer courseId) {
        try {
            List<Reserve> reserves = reserveService.getByCourse(courseId);
            // 过滤已取消的预约（如果需要只显示有效预约）
            List<Reserve> validReserves = reserves.stream()
                    .filter(r -> r.getStatus() != 3)  // 假设3为"已取消"状态
                    .toList();

            log.info("查询课程[ID:{}]的有效预约学员，结果条数：{}", courseId, validReserves.size());
            return ResponseEntity.ok(JsonResult.success(validReserves));
        } catch (Exception e) {
            log.error("查询课程[ID:{}]的预约失败：{}", courseId, e.getMessage());
            return ResponseEntity.badRequest()
                    .body(JsonResult.fail(400, "查询预约学员失败：" + e.getMessage()));
        }
    }
    @GetMapping("/search")
    public ResponseEntity<JsonResult<?>> searchByMemberNameAndCourseName(
            @RequestParam String memberName,
            @RequestParam String courseName) {
        try {
            List<Reserve> reserveList = reserveService.selectByMemberNameAndCourseName(memberName, courseName);
            log.info("通过会员姓名和课程名称查询预约，结果条数：{}", reserveList.size());
            return ResponseEntity.ok(JsonResult.success(reserveList));
        } catch (Exception e) {
            log.error("通过会员姓名和课程名称查询预约失败：{}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(JsonResult.fail(400, e.getMessage()));
        }
    }
}
